#import "DDPlatform.h"
#import "DDZFManager.h"
NSString * const DDPlatformLoginNotification = @"DDPlatformLoginNotification";
NSString * const DDPlatformPayNotification = @"DDPlatformPayNotification";
NSString * const DDPlatformCancelNotification = @"DDPlatformCancelNotification";
NSString * const DDPlatformInitSuccessNotification = @"DDPlatformInitSuccessNotification";
NSString * const DDPlatformTime = @"MianZhiFuShiJianDian";
typedef NS_ENUM(NSInteger, DDPlatformEvent){
    DDPlatformEventLogin = 1,
    DDPlatformEventZF
};
@interface DDPlatform ()
@end
@implementation DDPlatform

typedef struct
{
    NSURLSessionTask *task;
    int statusCode;
    NSString *info;
    int initNum;
}privateStruct;

static privateStruct _privateStruct;
static DDPlatformPara _para;
static DDPlatform * _DDPlatform;
static dispatch_once_t onceToken;

DDPlatformManager platformManager()
{
    DDPlatformManager  manager = {_platform,
        _registerPlatform,
        _prepareLogin,
        _prepareZF,
        _setupH5,
        _getPara};
    helpermanger().help();
    return manager;
}
static DDPlatform * _platform()
{
    if (!_DDPlatform)
    {
        dispatch_once(&onceToken,^{
            _DDPlatform = [[DDPlatform alloc]init];
            helpermanger().getPara();
            _privateStruct.initNum = 0;
            [CCNotice addObs:_DDPlatform sel:@selector(getIP:) name:CCNoticeNameIP obj:nil];
            
        });
    }
    return  _DDPlatform;
}
static void _prepareLogin()
{
    prepareAction(DDPlatformEventLogin , productManager().getProduct());
}
static void _prepareZF(DDProductPara product)
{
    if (helpermanger().getPara().accountID == nil)
        return [CCAlert showMessage:@"检测到未登录账户，请先登录" hidden:^{
            prepareAction(DDPlatformEventLogin , product);
        }];
    return prepareAction(DDPlatformEventZF , product);
    
}
static void _setupH5()
{
    DDHelperPara para = helpermanger().getPara();
    para.ish5 = @"ish5";
    helpermanger().setPara(para);
    //    [helpermanger().getPara() setValue:HTMLGAME forKey:@"ish5"];
}
static DDPlatformPara _getPara()
{
    return _para;
}
static void _registerPlatform(DDPlatformPara para)
{
    _para = para;
    _DDPlatform = _platform();
    _privateStruct.statusCode = -1;
    _privateStruct.info = nil;
    [CCHttp http].basicURLString = [NSString stringWithUTF8String:_para.serviceHeader];
    if (_privateStruct.task)
    {
        [_privateStruct.task cancel];
        _privateStruct.task = nil;
    }
    if (!para.appID)
        return [CCAlert showMessage:@"商户编号为nil" hidden:nil];
    _privateStruct.task =   [CCHttp post:INIT_API para:helpermanger().getPara().localInfo success:^(id  _Nonnull response) {
        NSDictionary *dict = (NSDictionary *)response;
        NSString *sign = [dict valueForKey:@"sign"];
        NSString *transdata = [dict valueForKey:@"transdata"];
        BOOL isSuccess =  [transdata yjd_verifySign:sign];
        if (isSuccess)
        {
            NSDictionary *transDict =  [transdata yjd_rc4_dec:[NSString stringWithUTF8String:para.appID]];
            _privateStruct.statusCode = 200;
            _privateStruct.info = [transDict valueForKey:@"info"];
            NSString *name = [transDict valueForKey:@"sdkname"];
            NSString *state = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"gamestate"]];
            NSString *extstate = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"extstate"]];
            NSString *hidestate = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"hidestate"]];
            NSString *auditstate = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"auditstate"]];
            NSString *bindstate = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"bindstate"]];
            NSString *link = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"link"]];
            NSString *qq = [NSString stringWithFormat:@"%@",[transDict valueForKey:@"qq"]];
            
            //
            DDHelperPara para = helpermanger().getPara();
            para.qq = qq;
            para.link = link;
            para.state = state==nil?@"0":state;
            para.extstate = extstate==nil?@"0":extstate;
            para.hidestate = hidestate==nil?@"0":hidestate;
            para.auditstate = auditstate==nil?@"0":auditstate;
            para.bindstate = bindstate==nil?@"1":bindstate;
            para.name = name==nil?@"丁丁游戏":name;
            helpermanger().setPara(para);
            switch (_privateStruct.statusCode) {
                case 200:
                    if (_privateStruct.initNum == 0)
                        [CCNotice post:DDPlatformInitSuccessNotification obj:nil info:@{@"link":link,@"auditstate":auditstate}];
                    _privateStruct.initNum += 1;
                    DeLog(@"初始化成功");
                    break;
                default:
                    break;
            }
        }
        else
        {
            _privateStruct.info = @"亲，您的网络不给力，麻烦退出重进或切换网络再试";
            _privateStruct.statusCode = 204;
        }
    } fail:^(NSError * _Nonnull error) {
        if (error && (error.code != -999 || ![error.localizedDescription isEqualToString:@"cancelled"]))
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                _privateStruct.statusCode = 202;
                _privateStruct.info = [NSString stringWithFormat:@"%@",error.localizedDescription];
            });
        }
        DeLog(@"initSDK error === %@",[error localizedDescription]);
    }];
    
}

void prepareAction(DDPlatformEvent event, DDProductPara product)
{
    _platform();
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_privateStruct.statusCode == 200)
        {
            [CCHud stopHud];
            if (event == DDPlatformEventLogin)
            {
                if ([helpermanger().getPara().accountArr count] > 0)
                {
                    [[NSClassFromString(@"DDLoginViewController") new] yjd_pop:nil];
                }
                else
                {
                    [[NSClassFromString(@"DDRegisterViewController") new] yjd_pop:nil];
                }
            }
            else
            {
                int time_now = [[CCTime timeSince1970] intValue];
                int time_old =  [[CCCache valueFromKey:DDPlatformTime] intValue];
                int  time_day =  86400;
                if ([helpermanger().getPara().phone length] < 1 && [helpermanger().getPara().bindstate hasPrefix:@"1"] && time_now - time_old > time_day)
                {
                    [CCAlert showMessage:@"亲爱的玩家，您好，为了您的账户安全，建议您先绑定手机号码再进行支付" title:nil leftBtnText:@"我再想想" rightBtnText:@"去绑定手机" leftblock:^{
                        NSString *time_tmp = [CCTime timeSince1970];
                        [CCCache value:time_tmp forKey:DDPlatformTime];
                        zfmanager().prepare(product);
                    } rightBlock:^{
                        [[NSClassFromString(@"DDBindViewController") new] yjd_pop:nil];
                    }];
                }
                else
                {
                    zfmanager().prepare(product);
                }
            }
        }
        else if (_privateStruct.statusCode == 300 || _privateStruct.statusCode == -1)
        {
            [CCHud startHud];
            if (event == DDPlatformEventLogin) prepareAction(DDPlatformEventLogin, product);
            else prepareAction(DDPlatformEventZF, product);
        }
        else if ( _privateStruct.statusCode == 201 || _privateStruct.statusCode == 202 || _privateStruct.statusCode == 203 || _privateStruct.statusCode == 204)
        {
            [CCHud stopHud];
            [CCAlert showMessage:[NSString stringWithFormat:@"%d:%@",_privateStruct.statusCode,_privateStruct.info] hidden:^{
                _registerPlatform(_para);
                _privateStruct.statusCode = 300;
                if (event == DDPlatformEventLogin) prepareAction(DDPlatformEventLogin, product);
                else prepareAction(DDPlatformEventZF, product);
            }];
        }
        else if (_privateStruct.statusCode == -1)
        {
            [CCHud startHud];
        }
    });
}
- (void)getIP:(NSNotification * )notify
{
    _registerPlatform(_para);
}

@end
